package com.fs.system.config;

import com.fs.common.util.RedisCache;
import com.fs.system.security.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.filter.CorsFilter;

/**
 * @author suke
 * @version 1.0
 * @title SpringSecurityConfiguration
 * @description  springSecurity的自定义配置类
 * @create 2024/7/25 10:14
 */
@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysPasswordProperties passwordProperties;

    //对密码进行加密    密码校验
    @Bean
    /*public BCryptPasswordEncoder passwordEncoder(){
        return new  BCryptPasswordEncoder();
    }*/
    public PasswordEncoder passwordEncoder(){
        return new MyPasswordEncoder();
    }



    //修改用户名,密码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //存放的密码: 密文
        //auth.inMemoryAuthentication().withUser("test").password(passwordEncoder().encode("test1")).roles("admin");
        //默认使用DaoAuthenticationProvider
        //auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());

        //使用MyDaoAuthenticationProvider
        auth.authenticationProvider(new MyDaoAuthenticationProvider(userDetailsService,redisCache,passwordEncoder(),passwordProperties));
    }


    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private CorsFilter corsFilter;


    @Autowired
    private TokenAuthenticationEntryPoint tokenAuthenticationEntryPoint;

    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity
                // CSRF禁用，因为不使用session
                .csrf().disable()
                // 禁用HTTP响应标头
                .headers().cacheControl().disable().and()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                .antMatchers("/login", "/register", "/captchaImage").permitAll()
                // 静态资源，可匿名访问
                .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
                .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();

        //添加过滤器
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        //添加跨域过滤器
        httpSecurity.addFilterBefore(corsFilter,JwtAuthenticationTokenFilter.class);

        //配置认证失败的入口
        httpSecurity.exceptionHandling().authenticationEntryPoint(tokenAuthenticationEntryPoint);

        //配置注销
        httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
    }
}
